local skynet = require "skynet"
local log = require "sky_log"
local DEF = require "room_define"
local service_table = {}

function service_table:init_table(table_info, room_config)
    self.player_list = {}
    self.player_nums = 0
    self.table = table_info
    self.table.room_config = room_config
    self.game_status = DEF.GAME_STATUS.READY

    self.machine = require "machine"
    self.machine:create_room(table_info)
end

function service_table:enter_game(agent, player_info)
    local ret = {}
    ret.match_res = {
        status = 1,
    }
    ret.table_id = self.table.table_id
    
    --坐下逻辑得到椅子号,这里省去这部分逻辑
    self.player_nums = self.player_nums + 1
    player_info.seat_id = self.player_nums
    player_info.online = true
    self.player_list[player_info.player_id] = player_info

   
    log.debug("self.table_info=", self.table)
    log.debug("self.player_nums=", self.player_nums)
    log.debug("self.player_list=", self.player_list)
    
    --接下来，服务器设置玩家自动准备(也可以客户端发送准备消息)
    self:player_ready(player_info.player_id)
    --把桌子的一些信息发送给玩家
    skynet.send(agent, "lua", "enter_game", skynet.self(), ret, 20)
   
    --游戏中，断线重连
    if self.game_status==DEF.GAME_STATUS.START then 
        self.machine:reconnect_game(player_info.player_id)
    end
 
end

--准备
function service_table:player_ready(player_id)
    self.player_list[player_id].ready = 1

    --[[
    local player_info2 = {
        agentFd=nil, ready=0, player_id=34567, username="test2",
        headimg_id=2, sex=2, gold=200, is_robot=true, seat_id=2,
    }
    self.player_nums = self.player_nums + 1
    self.player_list[player_info2.player_id] = player_info2
    --]]

    local args = {
        roomCode = self.table.table_id,
        control_mode = self.table.control_mode or 0,
        player_num = self.player_nums,
        player_list = self.player_list,   --兼容测试代码，后续移除
        room_config = self.table.room_config
    }
   
    if self.player_nums>=self.table.room_config.min_player then 
        self.machine:game_start(args)
        self.game_status = DEF.GAME_STATUS.START
    end
end

function service_table:disconnect(player_id)
    log.debug("player_id=", player_id)
    self.player_nums = self.player_nums - 1
    self.player_list[player_id].online = false
    self.machine:disconnect(player_id)
end

function service_table:handle_msg(agent, paid_id, msg_title, msg_data)
    self.machine:handle_msg(agent, msg_title, msg_data)
end 

--start
skynet.start(function()
    --session是当前服务地址  address是源服务(发消息来的服务)地址
    skynet.dispatch("lua", function(session, address, cmd, ...)
        --log.info("service_table dispatch cmd=", cmd)
        --log.info("service_table dispatch session=", session)
        --log.info("service_table dispatch address=", address)
        local f = service_table[cmd]
        if f then  
            skynet.retpack(f(service_table, ...))
        else
            log.error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)
end)

return service_table
